from jira import JIRA, Issue
import re, os
import datetime


def logprint(*args, sep=" ", end="\n"):
    print(datetime.datetime.now(), *args, sep=" ", end="\n")


def get_config_file(filename: str = None):
    if filename is None:
        filepath = os.path.abspath(__file__)
        file = os.path.split(filepath)[0] + "/config_dev/config.ini"
    else:
        file = filename
    return file


def get_server_config(filename: str = None):
    import configparser

    config = configparser.ConfigParser()
    try:
        with open(get_config_file(filename)) as fp:
            config.read_file(fp)
            return (
                config.get("Account", "url"),
                config.get("Account", "user"),
                config.get("Account", "passwd"),
            )
    except Exception as e:
        raise Exception(f"Failed to open configuration file:{get_config_file()} -  {e}")
    pass


def get_section_config_by_type(asection_type: str, filename: str = None):
    import configparser

    config = configparser.ConfigParser()
    try:
        with open(get_config_file(filename)) as fp:
            config.read_file(fp)
            sections = config.sections()
            section_configs = []
            for section in sections:
                if (
                    section.startswith("Report")
                    and config.get(section, "Type") == asection_type
                ):
                    section_type = config.get(section, "Type")
                    section_enable = config.getboolean(section, "Enable")
                    section_jql = config.get(section, "JQL")
                    section_file = config.get(section, "File")
                    section_sheet = config.get(section, "Sheet")
                    section_configs.append(
                        (
                            section,
                            section_type,
                            section_enable,
                            section_jql,
                            section_file,
                            section_sheet,
                        )
                    )
            return section_configs
    except Exception as e:
        raise Exception(f"Failed to open configuration file:{get_config_file()} -  {e}")


def get_ca_configs(config_file: str = None):
    ca_configs = get_section_config_by_type("CA", config_file)
    return ca_configs


def get_epic_configs(config_file: str = None):
    epic_configs = get_section_config_by_type("EPIC", config_file)
    return epic_configs


def get_task_configs(config_file: str = None):
    task_configs = get_section_config_by_type("Task", config_file)
    return task_configs


def init_jira_connection(config_file: str = None):
    url, user, passwd = get_server_config(config_file)
    jira_obj = JIRA(server=url, auth=(user, passwd))
    if jira_obj is None:
        raise Exception("init_jira_connection failure", url, user, passwd)
    logprint("init_jira_connection() success!")
    return jira_obj


def query_jira_issue(jira: JIRA, FBPKey: str) -> JIRA.issue:
    issue = jira.issue(FBPKey)
    if issue is None:
        raise Exception("querey_jira_issue failure! {FBPKey}")
    return issue


def exectue_jql(jira: JIRA, jql):
    logprint(f"execut_jql() start ...{jql} ")
    issue_list = jira.search_issues(jql, maxResults=2000, validate_query=True)
    if not issue_list:
        logprint(f"execute_jql failure -jql={jql}")
    else:
        logprint(f"execute_jql() finished! Total: {len(issue_list)} records")
    return issue_list


def getAssignee(issue: Issue):
    return (
        issue.fields.assignee.displayName if issue.fields.assignee else "Not Assigned"
    )


def getStatus(issue: Issue):
    return issue.fields.status.name if issue.fields.status else ""


def getItemId(issue: Issue):
    return issue.fields.customfield_38702 if issue.fields.customfield_38702 else ""


def getKey(issue: Issue):
    return issue.key if issue.key else ""


def getIssueType(issue: Issue):
    return issue.fields.issuetype.name if issue.fields.issuetype else ""


def getSummary(issue: Issue):
    return issue.fields.summary if issue.fields.summary else ""


def getParentData(issue: Issue):
    pareant_summary = issue.fields.parent.fields.summary if issue.fields.parent else ""
    parent_statue = (
        issue.fields.parent.fields.status.name
        if issue.fields.parent and issue.fields.parent.fields.status
        else ""
    )
    return pareant_summary, parent_statue


def getTimeRemaining(issue: Issue):
    return issue.fields.customfield_43291 if issue.fields.customfield_43291 else 0


def getTimeLogged(issue: Issue):
    return issue.fields.customfield_43290 if issue.fields.customfield_43290 else 0


def getTimeAll(issue: Issue):
    return getTimeRemaining(issue) + getTimeLogged(issue)


def getOriginalEstimate(issue: Issue):
    return issue.fields.customfield_43292 if issue.fields.customfield_43292 else 0


def getStartFB(issue: Issue):
    return int(issue.fields.customfield_38694) if issue.fields.customfield_38694 else 0


def getEndFB(issue: Issue):
    return int(issue.fields.customfield_38693) if issue.fields.customfield_38693 else 0


def getFbCommitStatus(issue: Issue):
    return issue.fields.customfield_38727 if issue.fields.customfield_38727 else ""


def getTeam(issue: Issue):
    if issue.fields.customfield_29790:
        if issue.fields.customfield_29790.name:
            return issue.fields.customfield_29790.name
    else:
        return ""


def getfeatureInfor(itemID: str):
    itemID = itemID.replace("_", "-")
    ids = itemID.split("-")
    if itemID.startswith("CNI") or (
        itemID.startswith("CB")
        and ("-SR-" in itemID or "-CR-" in itemID or "-5G-" in itemID)
    ):
        if len(ids) == 1:
            return "-".join(ids[:1]), "-".join(ids[:1]), "-".join(ids[:1])
        elif len(ids) == 2:
            return "-".join(ids[:2]), "-".join(ids[:2]), "-".join(ids[:2])
        elif len(ids) == 3:
            return "-".join(ids[:2]), "-".join(ids[:3]), "-".join(ids[:3])
        else:
            return "-".join(ids[:2]), "-".join(ids[:3]), "-".join(ids[:4])

    else:
        if len(ids) == 1:
            return "-".join(ids[:1]), "-".join(ids[:1]), "-".join(ids[:1])
        elif len(ids) == 2:
            return "-".join(ids[:1]), "-".join(ids[:2]), "-".join(ids[:2])
        else:
            return "-".join(ids[:1]), "-".join(ids[:2]), "-".join(ids[:3])


def getSprintData(issue: Issue):
    sprint_field = issue.fields.customfield_11990
    if sprint_field:
        sprint_info = sprint_field[-1]  # Get the most recent sprint
        sprint_name = re.search(r"name=([^,]+)", sprint_info).group(1)
        sprint_start_date = re.search(r"startDate=([^,]+)", sprint_info).group(1)
        sprint_end_date = re.search(r"endDate=([^,]+)", sprint_info).group(1)
        return sprint_name, sprint_start_date, sprint_end_date
    return "", "", ""


def getSprintFB(sprint: str):
    match = re.search("FB", sprint)
    if match:
        result = sprint[match.start() :]
        return result
    else:
        return sprint


# CA fields
def getPlannedRelease(issue: Issue):
    return (
        issue.fields.customfield_38724[0].value
        if issue.fields.customfield_38724
        else ""
    )


def getBusinessPriority(issue: Issue):
    return issue.fields.customfield_38716 if issue.fields.customfield_38716 else ""


def getFbCommitStatus(issue: Issue):
    return issue.fields.customfield_38758 if issue.fields.customfield_38758 else ""


def getStretchReason(issue: Issue):
    return (
        issue.fields.customfield_43893.value if issue.fields.customfield_43893 else ""
    )


def getDelayReason(issue: Issue):
    return issue.fields.customfield_38755 if issue.fields.customfield_38755 else ""


def getReleaseCommittedFB(issue: Issue):
    return (
        f"FB{issue.fields.customfield_43490.value}"
        if issue.fields.customfield_43490
        else ""
    )


def getReleaseCommittedStatus(issue: Issue):
    return (
        issue.fields.customfield_38728.value if issue.fields.customfield_38728 else ""
    )


def getCompetenceArea(issue: Issue):
    return (
        issue.fields.customfield_38690.value if issue.fields.customfield_38690 else ""
    )


def getFOTLeader(issue: Issue):
    return (
        issue.fields.customfield_38695.displayName
        if issue.fields.customfield_38695
        else ""
    )


def getReporter(issue: Issue):
    return issue.fields.reporter.displayName if issue.fields.reporter else ""


def getText2(issue: Issue):
    return issue.fields.customfield_38727 if issue.fields.customfield_38727 else ""


def main():
    pass


if __name__ == "__main__":
    main()
